/**
 * @Copyright: Interactive Business Solution Pte Ltd, Singapore
 * @Author: Li Wen, 2007-12-07
 * @Version: 071207.001
 * Monitors availablity of a Http or HTTPS-based service
 */
package com.ibsol.control
{
	import air.net.URLMonitor;
	import mx.managers.CursorManager;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.StatusEvent;
	import flash.net.URLRequest;
	
	public class ConnectionManager extends EventDispatcher
	{
		private var _status:Boolean;
		/**
		 * Checks the connection status with specific URL address, class constructor
		 * @param:	testURL:String	url address needs to be tested
		 * @return:	void
		 */
		public function ConnectionManager(testURL:String)
		{
			var request:URLRequest = new URLRequest();
			request.method = "HEAD";
			request.url = testURL;
			var monitor:URLMonitor = new URLMonitor(request);
			monitor.addEventListener(StatusEvent.STATUS, statusChangedHandler);
			//Show busy cursor
			CursorManager.setBusyCursor();
			monitor.start();
		}
		/**
		 * Gets connection status, if the connection is successful then return true, else return false
		 * @param:	null
		 * @return:	Boolean
		 */
		public function get status():Boolean
		{
			return this._status;
		}
		/**
		 * Handles connection status change, dispatch "statusChanged" event after getting result.
		 * During connectivity checking, a busy cursor is shown on the screen
		 * @param:	status:StatusEvent		server status variable
		 * @return:	void
		 */
		private function statusChangedHandler(status:StatusEvent):void
		{
			if(status.code == "Service.unavailable")
			{
				this._status = false;
			}
			else
			{
				this._status = true;
			}
			var e:Event = new Event("statusChanged",true);
			dispatchEvent(e);
			CursorManager.removeBusyCursor();
		}
	}
}